package edu.whut.mall.portal.controller;

import edu.whut.mall.common.api.CommonResult;
import edu.whut.mall.portal.service.impl.UserServiceImpl;
import edu.whut.mall.portal.service.impl.WeChatServiceImpl;
import edu.whut.mall.portal.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * @ClassName: WeChatController
 * @Description: 微信相关控制器
 * @Author: lvfanbing
 * @Date: 2020-05-29 20:27
 * @Version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/wechat")
@Api(value="微信业务相关控制器",tags = {"微信业务相关控制器"})
public class WeChatController {


    private final UserServiceImpl userService;
    private final WeChatServiceImpl weChatService;


    @ApiOperation("微信授权登录")
    @PostMapping("/authorizeLogin")
    public CommonResult authorizeLogin(@NotBlank @RequestParam("code") String code) {
        String session = weChatService.authorizationLogin(code);
        if (session == null) {
            return CommonResult.failed("授权失败");
        }
        return CommonResult.success(session,"授权成功");
    }

    @ApiOperation("获取用户基本信息")
    @PostMapping("/getUserInfoFromWx")
    public CommonResult getUserInfoFromWx(@NotBlank @RequestParam("encrydata") String encrydata,
                                          @NotBlank @RequestParam("ivdata") String ivdata,
                                          @NotBlank @RequestParam("session") String session) {
        UserVo userVo = weChatService.getUserInfoFromWx(encrydata, ivdata, session);
        if (userVo != null) {
            return CommonResult.success(userVo, "获取用户信息成功");
        }
        return CommonResult.failed("获取用户信息失败");
    }

    @ApiOperation("获取用户电话号码")
    @PostMapping("/getUserPhoneNumberFromWx")
    public CommonResult getUserPhoneNumberFromWx(@NotBlank @RequestParam("encrydata") String encrydata,
                                                 @NotBlank @RequestParam("ivdata") String ivdata,
                                                 @NotBlank @RequestParam("session") String session) {
        String userPhoneNumber = weChatService.getUserPhoneNumberFromWx(encrydata, ivdata, session);
        if (userPhoneNumber == null) {
            return CommonResult.failed("获取用户电话号码失败");
        }
        return CommonResult.success("获取用户电话号码成功");
    }
}
